<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 2017.6.14 magento 数据接口
 */
class Magentodata
{

    function __construct()
    {
		$this->CI =& get_instance();
        $this->db1 = $this->CI->load->database('default', TRUE);
		$this->db2 = $this->CI->load->database('amazondata', TRUE);
        $this->CI->load->library('Amazondata');
        $this->amazondata = new amazondata();
    }

    // public function gettoken($id){
    // 	 $row = $this->db1->get_where("d_shop","id={$id}")->result_array();
    // 	 foreach ($row as $v) {
    //   $shopid=$v['id'];
    // 	$name=$v['name'];
    //   $data=json_decode($v['amazonkey'],true);
    //   $token=$data['magentotoken'];
    // }
    // return $token;
    // }
	
	/******更新网站SKU信息**************/
	public function updatemagentwebdata()
	{
		$list = $this->db1->select('uploadImages,id')->get_where("db_magento_productlist","isupload = 1")->result_array();
		if(count($list))
		{
			foreach($list as $key=>$rs)
			{
				//先要处理图片信息
				include_once(dirname(__FILE__)."/../../fuman/upfile/TieTuKu.class.php");	//获取外部图片库API接口
				$sdk=new TTKClient('9ed9b5d096d32d5460bef0744a11fd13e21ae960','66fdb66e6cae1f2d2d16560e3b7b2da19a10e9d4');

				
				if($rs["uploadImages"])
				{
					$uploadImages = explode("|",$rs["uploadImages"]);
					$newimageslist = "";
					foreach($uploadImages as $key=>$ImagesUrl)
					{
						$result=$sdk->uploadFromWeb('1434082',$ImagesUrl);
						$resultstr = json_decode($result,true);
						$newimageslist[] = $resultstr["linkurl"];
					}
					if(count($newimageslist))
					{
						$this->db1->update("db_magento_productlist",array("images"=>implode("|",$newimageslist)),"id='".$rs["id"]."'");
						
					}
				}

			}
		}

		$list = $this->db1->get_where("db_magento_productlist","isupload = 1")->result_array();
		if(count($list))
		{
			$post = "";
			$update="";
			foreach($list as $key=>$rs)
			{
				if($rs["updateData"]){
				$post[$key]["product_id"] = $rs["product_id"];
				$post[$key]["parent_id"] = $rs["parent_id"];
				$post[$key]["sku"] = $rs["sku"];
				$post[$key]["updateData"] = $rs["updateData"];
				$post[$key]["is_update"]= 1;
				$post[$key]["webname"] = $rs["webname"];
				$post[$key]["inserttime"] =time();
				$post[$key]["images"] = $rs["images"];

				$update[$key]["id"] = $rs["id"];
				$update[$key]["isupload"] =2;
				}

			}

			if(count($post))
			{
				$this->db2->insert_batch('db_magento_productlist',$post);
				$this->db1->update_batch('db_magento_productlist',$update,"id");

			}
		}
	}

	/******获取更新完成的SKU到本地****/
	public function getRemotedata()
	{
		$list = $this->db2->get_where("db_magento_productlist","is_update = 2")->result_array();
		if(count($list))
		{
			foreach($list as $key=>$rs)
			{
				$message = json_decode($rs["message"],true);
				if($message["product_id"] >0)
				{
					$post="";
					$post["product_id"] = $message["product_id"];
					$post["product_url"] = $message["url"];
					$this->db1->update('db_magento_productlist',$post,"webname='".$rs["webname"]."' AND sku='".$rs["sku"]."' ");
					$this->db2->update('db_magento_productlist',array("is_update"=>3),"id='".$rs['id']."'");
					$this->CI->fun->update_develop_addtime($rs["sku"],"174",$message["url"]); //自动更新上架信息
				}else{
					//当更新出错,显示编辑，重新上传按钮
					$post="";
					$post["isupload"] = 3;
					$post["updateData"] = $rs["message"];
					$this->db1->update('db_magento_productlist',$post,"webname='".$rs["webname"]."' AND sku='".$rs["sku"]."' ");
					$this->db2->update('db_magento_productlist',array("is_update"=>3),"id='".$rs['id']."'");
				
				}
				
			}
		}
		echo "OK";
		die;
	}

    public function getdata()
    {

        // $token=urlencode($token);
        $to = time();
        $from = $to - 3600 * 24 * 3;
        $url = "http://network.pokemoncos.com/data/ordertoerp.php?from={$from}&to={$to}";
        var_dump($url);
        $list = file_get_contents($url);
        $xml = simplexml_load_string($list);
        $data = json_decode(json_encode($xml), TRUE);

        $shopname = array();
        $shopid = array();
        $row = $this->db1->get_where("d_shop", "platfromname='Magento'")->result_array();

        foreach ($row as $v) {
            $datax = json_decode($v['amazonkey'], true);
            if (isset($datax['magentotoken'])) {
                $key = $datax['magentotoken'];
            } else {
                continue;
            }


            $shopid[$key] = $v['id'];
            $shopname[$key] = $v['name'];
        }

        if ($data['code'] == 0) {
            //没有订单
            exit;
        }
        $dataorder = $data['allorder']['order'];
		//循环插入
        foreach ($dataorder as $value) {
            unset($orderkey);
            $orderkey = $value['platform'];


            if (!array_key_exists($orderkey, $shopid)) {
                continue;
            }

//查询订单是否已被导入

            $sql = "SELECT * FROM db_order_list WHERE tradeid='" . $value['increment_id'] . "' AND shopid='" . $shopid[$orderkey] . "'";
            $rorder = $this->db1->get_one($sql);
            if ($rorder) {
                continue;
            }


            $skuarr = json_decode($value['buyer_proudct_sku'], true);
            $pprice = json_decode($value['price'], true);

            foreach ($skuarr as $key => $sku) {
                $sku = trim($this->selectsku($sku));
                $check = $this->db1->get_where("db_goods", "goods_sku='{$sku}'")->result_array();
                if (empty($check)) {
                    $checklist = $this->db1->get_where("db_goods", "cognatelist like '%,{$sku},%'")->result_array();

                    if (empty($checklist)) {
                        //插入产品

                        // $productalljson= json_encode($value['productall']);

                        // $this->addproduct($productalljson);
                    } else {
                        $skuarr[$key] = $checklist[0]['goods_sku'];
                    }
                }

            }

//准备插入信息
            $postdata = "";
            $postdata["order_sn"] = $this->amazondata->getNo('magento', $value['increment_id'], $shopid[$orderkey]);
            $postdata["dates"] = date("Y-m-d");
            $postdata["order_status"] = 2;
            $postdata["order_source"] = '正常订单';
            $postdata['shipping_status'] = 0;
            $postdata["customerid"] = addslashes(trim($value['buyer_name']));

            $postdata["consignee"] = addslashes($value['buyer_name']);
            $postdata["country"] = $value['buyer_country'];
            $postdata["country_code"] = $value['buyer_country'];
            $rscountry = $this->db1->get_where("d_chinaexpress", "NAME='" . $value['buyer_country'] . "'")->result_array();
            if (isset($rscountry[0]["id"])) {
                $postdata["country_cn"] = $rscountry[0]["FILED1"];
            } else {
                $postdata["country_cn"] = '';
            }

            $postdata["province"] = gettype($value['buyer_region']) == 'string' ? addslashes(trim($value['buyer_region'])) : '';
            $postdata["city"] = gettype($value['buyer_city']) == 'string' ? addslashes(trim($value['buyer_city'])) : '';
            $postdata["address"] = addslashes(trim(gettype($value['buyer_street']) == 'string' ? $value['buyer_street'] : ''));
            $postdata["address2"] = '';
            $postdata["zipcode"] = gettype($value['buyer_code']) == 'string' ? $value['buyer_code'] : '';
            $postdata["tel"] = gettype($value['buyer_tel']) == 'string' ? $value['buyer_tel'] : '';
            $postdata["mobile"] = '';
            $postdata["email"] = isset($value['buyer_email']) == 'string' ? $value['buyer_email'] : '';
            $postdata["shopid"] = $shopid[$orderkey];
            $rshop = $this->db1->get_where("d_shop", "id=" . $shopid[$orderkey])->result_array();
            $postdata["shopname"] = $rshop[0]["name"];
            $postdata["shopoper"] = $rshop[0]["updateoper"];

            $postdata["moneytype"] = $value['receipt_currency'];
            $exchange = $this->db1->get_where("d_moneyrate", "name='{$value['receipt_currency']}'")->result_array();
            if ($exchange[0]["rate"]) {
                $exchangerate = $exchange[0]["rate"];
            } else {
                $exchangerate = 1;
            }
            //$postdata["tradeid"] = $TransactionID;
            $postdata["tradeid"] = $value['increment_id'];
            $postdata["postageservice"] = $ShippingDetails['ShippingServiceOptions'][0]['ShippingService'] ? $ShippingDetails['ShippingServiceOptions'][0]['ShippingService'] : NULL;
            $postdata['shipping_id'] = '';
            $postdata['shipping_name'] = '';
            $postdata['shipping_time'] = '';
            $shipping_amount = $value['shipping_amount'];
            if ($shipping_amount == null) $shipping_amount = 0;
            $postdata["goods_originask"] = $value['receipt_amount'] - $shipping_amount;//订单原始金额
            $postdata["goods_amount"] = ($value['receipt_amount'] - $shipping_amount) * $exchangerate;//订单rmb
            $postdata["shipping_fee"] = $shipping_amount * $exchangerate;//运费rmb
            $postdata["shipping_originask"] = $shipping_amount;//运费原始金额
            $postdata["add_time"] = time();
            $postdata["ordertime"] = $value['order_creattime'];
            $postdata["saleschannel"] = 'magento';
            $postdata["pay_fee"] = $value['receipt_amount'] * 0.015 * $exchangerate;
            $postdata['pack_fee'] = '';
            $postdata["platform_fee"] = $value['receipt_amount'] * 0.10 * $exchangerate;
            $postdata["surplus"] = "";
            $postdata["paypalmail"] = '';
            $postdata['platformID'] = $rshop[0]['platfrom'];//平台
            $postdata['moneyrate'] = $exchangerate;//汇率


            $payid = gettype($value['comment']) == 'array' ? '' : $value['comment'];

            $ifa = substr($payid, -6, 4);
            if ($ifa == '</a>') {
                $payid = substr($payid, -23, 17);
            } else {
                if(substr($payid,-4,4)=='</a>')
                    $payid = substr($payid, -21,17);
                else
                    $payid = substr($payid, -19, 17);

            }
            $postdata["payid"] = $payid;
            //$postdata["platform_message"]=gettype($value['comment'])=='array'?'':$value['comment'];

            $postdata["payaccount"] = '';
            $buyer_product_qty = json_decode($value['buyer_product_qty']);

            $this->db1->trans_begin();
            try {
                $this->db1->insert("db_order_list", $postdata);

                $orderID = $this->db1->insert_id();

                $factorycode = $this->amazondata->factorycode();
                $weight = 0;
                // foreach($sell as $key=>$res)
                // {
                $skui = 0;
                $skunum = count($skuarr);
                foreach ($skuarr as $key => $sku) {
                    $sku = trim($sku);
                    $rgoods = $this->db1->get_where("db_goods", "goods_sku='" . $sku . "'")->result_array();

                    if (isset($rgoods[0]["goods_id"])) {
                        $goods_id = $rgoods[0]["goods_id"];
                        $g_weights = $rgoods[0]["g_weight"] ? $rgoods[0]["g_weight"] : 400;
                        $sweight = $buyer_product_qty[$skui] * $g_weights;
                        $weight = $weight + $sweight;
                        $costprice = 0;
                        /*****************成本价计算方式********
                         **  11、12开头定制的衣服按成本价计算
                         **  批量的sku 按关联价计算
                         **  外采购的衣服按成本价计算
                         *********************************/
                        if (is_numeric($sku) && preg_match('|^\d{8}$|', $sku))    //数字并且8位SKU并且11 12开头
                        {
                            $goodscode = substr($sku, 0, 2);//取开头2位数
                            if (in_array($goodscode, $factorycode))    //是否存在在工厂code
                            {
                                $costprice = $rgoods[0]["g_costprice"];    //定制衣服按成本价计算
                            }
                        } else {
                            //如果当前SKU不是8位，查询父SKU是不是8位并且11，12开头
                            if (is_numeric($rgoods[0]["goods_parent_sku"]) && preg_match('|^\d{8}$|', $rgoods[0]["goods_parent_sku"]))    //数字并且8位SKU并且11 12开头
                            {
                                $goodscodes = substr($rgoods[0]["goods_parent_sku"], 0, 2);//取开头2位数
                                if (in_array($goodscodes, $factorycode))    //是否存在在工厂code
                                {
                                    $costprice = $rgoods[0]["bulkprice"];    //批量按关联价计算
                                }
                            } else {
                                $costprice = $rgoods[0]["g_costprice"];
                            }
                        }


                    } else {
                        $goods_id = 0;
                        $costprice = 0;
                        $sweight = 400;
                    }
                    $postsell = "";
                    $postsell["order_id"] = $orderID;
                    $postsell["goods_id"] = $goods_id;
                    $postsell["goods_name"] = addslashes($rgoods[0]['goods_name']);
                    $postsell["goods_sn"] = $sku;
                    $postsell["costprice"] = $costprice;
                    $postsell["goods_number"] = $buyer_product_qty[$skui];
                    $postsell["goods_price"] = $pprice[$skui] * $exchangerate;
                    $postsell["goods_weight"] = $sweight;
                    $postsell["goods_amount"] = $pprice[$skui] * $buyer_product_qty[$skui] * $exchangerate;
                    $postsell["originsellprice"] = $pprice[$skui] ? $pprice[$skui] : 0;
                    $postsell["originsku"] = $sku;
                    $postsell["product_link"] = '';
                    //$postsell["sale_remark"]='';
                    $this->db1->insert("db_order_sell", $postsell);

                    if ($goods_id == 0) {
                        $this->db1->update("db_order_list", array("order_status" => 7), "order_id=" . $orderID);
                    }
                    if ($weight) {
                        $this->db1->update("db_order_list", array("orderweight" => $weight), "order_id=" . $orderID);
                    }
                    $skui++;
                }
                //更新日志
                $imgdata["goods_id"] = $orderID;    //订单ID
                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                $imgdata["createUid"] = 0;
                $imgdata["types"] = 3;
                $imgdata["content"] = 'magento接口自动新增订单,交易ID=' . $value['increment_id'];
                $imgdata["createUser"] = 'auto';
                $this->db1->query($this->db1->insert_string('db_goods_log', $imgdata));


                $this->db1->trans_commit();
            } catch (Exception $e) {
                $this->db1->trans_rollback();
                $msg = $e->getMessage();
                print_r($msg);
                exit;
            }


        }


    }
	
	//获取所有的站内商品信息
	public function getwebproduct()
	{
		$post="";
		$isuploadpost="";
		$product = $this->db2->get_where("db_magento_getproduct","isupload  = 0")->result_array();
		if(count($product)>0)
		{
			$i = 0;
			
			foreach($product as $key=>$res)
			{
				 $isuploadpost[$key]["isupload"] = 1;
				 $isuploadpost[$key]["id"] = $res["id"];

				 $check = $this->db1->get_where("db_magento_productlist", "webname='".$res['webname']."' AND sku = '".$res['sku']."' ")->result_array();
				 if($check)
				 {
					continue;
				 }else{
					$post[$i]['product_id'] = $res["product_id"];
					$post[$i]['parent_id'] = $res["parent_id"];
					$post[$i]['webname'] = $res["webname"];
					$post[$i]['is_open'] = $res["is_open"];
					$post[$i]['sku'] = $res["sku"];
					$post[$i]['name'] = $res["name"];
					$post[$i]['description'] = $res["description"];
					$post[$i]['short_description'] = $res["short_description"];
					$post[$i]['weight'] = $res["weight"];
					$post[$i]['currency'] = $res["currency"];
					$post[$i]['price'] = $res["price"];
					$post[$i]['special_price'] = $res["special_price"];
					$post[$i]['variant_name'] = $res["variant_name"];
					$post[$i]['meta_title'] = $res["meta_title"];

					$post[$i]['meta_keywords'] = $res["meta_keywords"];
					$post[$i]['base_image'] = $res["base_image"];
					$post[$i]['small_image'] = $res["small_image"];
					$post[$i]['thumbnail_image'] = $res["thumbnail_image"];
					$post[$i]['including'] = $res["including"];
					$post[$i]['fabric'] = $res["fabric"];
					$post[$i]['images'] = $res["images"];
					$post[$i]['product_url'] = $res["product_url"];

					$i = $i+1;
				 
				 }

				

			}



		
			if($i>0)
			{
				$this->db1->insert_batch('db_magento_productlist',$post);
			}
		
			if($isuploadpost){
				$this->db2->update_batch('db_magento_getproduct',$isuploadpost,"id");
			}
			
		}
	}

    public function addproduct($data)
    {
        $allproduct = json_decode($data, true);
        if (!isset($allproduct['productinfo']['0'])) {
            $product = $allproduct['productinfo'];
            //单一商品
            if (!isset($product['product_sku'])) {
                return 'no product!';
            }
            if (!isset($product['productname'])) {
                return 'no product!';
            }


//加入新产品
            $parentsku = $this->checkparentsku($product['product_sku']);
            $productjson = json_encode($product);
            $this->addparentproduct($parentsku, $productjson);


        } else {
//多个商品
            foreach ($allproduct['productinfo'] as $value) {
                if (!isset($value['product_sku'])) {
                    continue;
                }
                if (!isset($value['productname'])) {
                    continue;
                }
                if ($this->checksku($value['product_sku'])) {

//加入新产品	
                    $parentsku = $this->checkparentsku($value['product_sku']);
                    $productjson = json_encode($value);
                    $this->addparentproduct($parentsku, $productjson);


                }
            }

        }
    }

    public function checksku($sku)
    {

        $check = $this->db1->get_where("db_goods", "goods_sku='{$sku}'")->result_array();
        if (empty($check)) {
            $checklist = $this->db1->get_where("db_goods", "cognatelist like '%,{$sku},%'")->result_array();
            if (empty($checklist)) {
                return true;

            }
        }

        return false;
    }

    public function checkparentsku($sku)
    {
//判断是否有父级sku
        if (strpos($sku, '-') === false) {
            //没有- 子级和父级一样
            return $sku;
        } else {
            $parentsku = explode("-", trim($sku));
            return $parentsku[0];
        }
    }

    public function selectsku($sku)
    {
        if (strpos($sku, '(') === false) {
            return $sku;
        } else {
            $onesku = substr($sku, strpos($sku, '(') + 1);
            if (strpos($onesku, ')') == '7') {
                if (substr($onesku, 0, 2) == '12') {
                    return substr($onesku, 0, strpos($onesku, ')') + 1);
                }
                return $sku;
            }
            return $sku;
        }
    }


    public function addparentproduct($parentsku, $productjson)
    {
        $product = json_decode($productjson, true);

        $postdata = '';
        $postdata['p_parent_sku'] = $parentsku;
        $postdata['p_parent_name'] = $product['productname'];
        $postdata['p_en_goods_name'] = $product['productname'];
        $postdata['p_yz'] = 0;
        $postdata['p_bigclassid'] = 1;
        $postdata['p_secondclassid'] = 14;
        $postdata['p_threeclassid'] = '';
        $postdata['p_goods_brand'] = null;
        $postdata['p_costprice'] = 0;
        $postdata['p_procurement'] = 15;
        $postdata['p_inventory_day'] = 15;
        $postdata['p_weight'] = 400;
        $postdata['p_sellprice'] = $product['price'];
        $postdata['p_pd_length'] = '';
        $postdata['p_pd_width'] = '';
        $postdata['p_pd_height'] = '';
        $postdata['p_pd_declare_value'] = '';
        $postdata['p_goodstypeID'] = 0;
        $postdata['p_sale_status'] = 2;
        $postdata['p_updatetime'] = date('Y-m-d H:i:s', time());
        $postdata['p_intime'] = date('Y', time());
        $postdata['p_createID'] = 0;
        $postdata['p_createUser'] = 0;
        $postdata['p_supplier'] = 3;
        $postdata['p_checkman'] = null;
        $postdata['p_buyer'] = null;
        $postdata['standard'] = null;
        $postdata['memo'] = 'magento订单导入时自动创建';
        $where = array('p_parent_sku' => $parentsku);
        $rsdbred = $this->db1->get_where('db_goods_parent', $where)->result_array();
        $this->db1->trans_begin();
        if (count($rsdbred) == 0)    //没有母商品
        {
            $likesql = "select * from db_goods where goods_sku like '{$parentsku}%';";
            $likesku = $this->db1->query($likesql)->result_array();

            if (count($likesku) == 0) {
                $this->db1->query($this->db1->insert_string('db_goods_parent', $postdata));
                $parentID = $this->db1->insert_id();
            } else {
                foreach ($likesku as $v) {
                    $parentID = $v['goods_parentID'];
                    break;
                }


            }


        } else {


            //更新母商品
            $this->db1->update('db_goods_parent', $postdata, 'p_parent_id=' . $rsdbred[0]["p_parent_id"]);
            $parentID = $rsdbred[0]["p_parent_id"];
        }

        //插入子商品

        /*********子商品**********/
        $postdata = "";
        $postdata["goods_parentID"] = $parentID;
        $parentList = $this->db1->get_where('db_goods_parent', 'p_parent_id=' . $parentID)->result_array();
        $postdata['goods_parent_sku'] = $parentList[0]["p_parent_sku"];
        $postdata['goods_name'] = $product['productname'];
        $postdata['yz'] = 0;
        $postdata['goods_sku'] = $product['product_sku'];
        $postdata['g_bigclassid'] = 1;
        $postdata['g_secondclassid'] = 14;
        $postdata['g_threeclassid'] = '';
        $postdata['en_goods_name'] = $product['productname'];
        $postdata['goods_brand'] = null;
        $postdata['g_costprice'] = 0;
        $postdata['g_procurement'] = 15;
        $postdata['g_inventory_day'] = 15;
        $postdata['g_weight'] = 400;
        $postdata['g_sellprice'] = $product['price'];
        $postdata['g_pd_length'] = '';
        $postdata['g_pd_width'] = '';
        $postdata['g_pd_height'] = '';
        $postdata['g_pd_declare_value'] = '';
        $postdata['g_goodstypeID'] = 0;
        $postdata['g_sale_status'] = 2;
        $postdata['g_updatetime'] = date('Y-m-d H:i:s', time());
        $postdata['g_checkman'] = '刘艺';
        $postdata['g_buyer'] = '刘艺';
        $postdata['g_createID'] = 0;
        $postdata['g_createUser'] = 0;
        $postdata['standard'] = null;
        $postdata['memo'] = 'magento订单导入时自动创建';
        $postdata['g_supplier'] = 3;
        $postdata['cognatelist'] = '';

        $where = array('goods_sku' => $product['product_sku']);
        $rsdb = $this->db1->get_where('db_goods', $where)->result_array();
        if (count($rsdb) == 0)    //没有商品
        {
            $this->db1->query($this->db1->insert_string('db_goods', $postdata));
            $goods_id = $this->db1->insert_id();
        } else {
            $this->db1->update('db_goods', $postdata, 'goods_id=' . $rsdb[0]["goods_id"]);
            $goods_id = $rsdb[0]["goods_id"];
        }
        $imgdata = "";
        $imgdata["goods_id"] = $goods_id;
        $imgdata["updatetime"] = date("Y-m-d H:i:s");
        $imgdata["createUid"] = 0;
        $imgdata["types"] = 1;
        $imgdata["content"] = 'magento订单导入时自动创建';
        $imgdata["createUser"] = 0;
        $this->db1->query($this->db1->insert_string('db_goods_log', $imgdata));


        //更新默认仓库


        $where = array('goods_id' => $goods_id);
        $rsdbstock = $this->db1->get_where('db_goods_stock', $where)->result_array();
        if (!$rsdbstock) {
            $imgdata = "";
            $imgdata["goods_id"] = $goods_id;
            $imgdata["storage_name"] = '一号仓';
            $imgdata["storage_id"] = 1;
            $imgdata["stock"] = 0;
            $imgdata["in_transit"] = 0;
            $imgdata["positions"] = '';
            $this->db1->query($this->db1->insert_string('db_goods_stock', $imgdata));
        }


        if ($this->db1->trans_status() === FALSE) {
            $this->db1->trans_rollback();
        } else {
            $this->db1->trans_commit();
        }


    }

    public function magento_v1_shopify($webname){
            //首先获取要转数据的网站
            //第二步根据网站分析出来所使用的语言
              //先确定.的位置 然后截取后面的部分
              
              $pos = strpos($webname,'.');
              if(!$pos) {
                echo "您所选择的不是magento网站，请重新选择";
                return 'error';
              }
      
              $language = substr($webname, $pos+1);
             
 
            //第三步 根据语言确定基础数据
            //定义性别数组 由于性别需要根据 语言来处理
            if($language == 'fr'){
                $gender = array(
                    '0' =>  'Femme' , 
                    '1' =>  'Homme'
                    );
                $gdn = 'Sexe';
                $szn = 'Taille';
                $costumetage = "costume";
                $shoetage = 'chaussures';
                $search_costume = 'costume';
                $search_shoe = 'chaussure';
            }
            if($language ==  'com' || $language == 'co.uk'){
                $gender = array(
                    '0' => 'Female',
                    '1' => 'Male'
                    );
                $gdn = 'Gender';
                $szn = 'Size';
                $costumetage = 'costume';
                $shoetage = 'shoes';
                $search_costume = 'Costume';
                $search_shoe = 'Shoes';
            }
            if($language == 'de'){
                $gender = array(
                    '0' => 'Damen',
                    '1' => 'Herren'
                    );
                $gdn = 'Geschlecht';
                $szn = 'Größe';
                $costumetage = 'Herrengröße,Damengröße';
                $shoetage = 'Schuhegröße';
                $search_costume = 'Kostüm';
                $search_shoe = 'Schuhe';
            }


            //定义尺码
            $chart = array();
            $clothessize = array();
            $shoessize = array();

            //衣服尺码不区分语言 使用同一标准
            $clothessize[] = 'XS';
            $clothessize[] = 'S';
            $clothessize[] = 'M';
            $clothessize[] = 'L';
            $clothessize[] = 'XL';
            $clothessize[] = 'XXL';
            $clothessize[] = 'XXXL';

            //衣服尺码添加入尺码数组
            $chart[1] = $clothessize;

            //定义鞋子尺码
            $shoessize[] = $gender[0].' 34(Eur)4.5(US)';
            $shoessize[] = $gender[0].' 35(Eur)5(US)';
            $shoessize[] = $gender[0].' 35.5(Eur)5.5(US)';
            $shoessize[] = $gender[0].' 36(Eur)6(US)';
            $shoessize[] = $gender[0].' 37(Eur)6.5(US)';
            $shoessize[] = $gender[0].' 37.5(Eur)7(US)';
            $shoessize[] = $gender[0].' 38(Eur)7.5(US)';
            $shoessize[] = $gender[0].' 38.5(Eur)8(US)';
            $shoessize[] = $gender[0].' 39(Eur)8.5(US)';
            $shoessize[] = $gender[0].' 39.5(Eur)9(US)';
            $shoessize[] = $gender[0].' 40(Eur)9.5(US)';
            $shoessize[] = $gender[0].' 41(Eur)10(US)';
            $shoessize[] = $gender[0].' 42(Eur)10.5(US';
            $shoessize[] = $gender[1].' 38(Eur)5.5(US)';
            $shoessize[] = $gender[1].' 38.7(Eur)6(US)';
            $shoessize[] = $gender[1].' 39.3(Eur)6.5(US)';
            $shoessize[] = $gender[1].' 40(Eur)7(US)';
            $shoessize[] = $gender[1].' 40.5(Eur)7.5(US)';
            $shoessize[] = $gender[1].' 41(Eur)8(US)';
            $shoessize[] = $gender[1].' 42(Eur)8.5(US)';
            $shoessize[] = $gender[1].' 42.5(Eur)9(US)';
            $shoessize[] = $gender[1].' 43(Eur)9.5(US)';
            $shoessize[] = $gender[1].' 44(Eur)10(US)';
            $shoessize[] = $gender[1].' 44.5(Eur)10.5(US)';
            $shoessize[] = $gender[1].' 45(Eur)11(US)';
            $shoessize[] = $gender[1].' 46(Eur)11.5(US)';
            $shoessize[] = $gender[1].' 46.5(Eur)12(US)';
            $shoessize[] = $gender[1].' 47(Eur)12.5(US)';

            //将鞋子尺码增加到尺码里面
            $chart[4] = $shoessize;

            //定义数据
            $data = array();
            //定义头部
            $head = array();
            //手柄是每个产品的唯一名称。它们可以包含字母，破折号和数字，但不包含空格。每个产品的URL都使用一个句柄。
            $head[] = 'Handle';
            //您的产品的标题
            $head[] = 'Title';
            //以HTML格式描述产品。这也可以是没有任何格式的纯文本。
            $head[] = 'Body (HTML)';
            //产品供应商的名称。
            $head[] = 'Vendor';
            //产品类型
            $head[] = 'Type';
            //用于标记产品的以逗号分隔的标签列表。大多数电子表格应用程序会自动为您添加标签周围的引号。如果您使用纯文本编辑器，则需要手动添加引号。
            $head[] = 'Tags';
            //说明产品是否在您的网上商店上发布。TRUE如果产品在您的在线商店上发布，或者产品对您的在线商店FALSE隐藏，则有效值为。将该字段留空将发布产品。
            $head[] = 'Published';
            //如果产品有选项，请输入其名称。
            $head[] = 'Option1 Name';
            $head[] = 'Option1 Value';
            $head[] = 'Option2 Name';
            $head[] = 'Option2 Value';
            $head[] = 'Option3 Name';
            $head[] = 'Option3 Value';
            //产品或变体的SKU。这用于跟踪库存跟踪服务。
            $head[] = 'Variant SKU';
            //产品或变体的重量，单位为克。不要添加测量单位，只是数字。
            $head[] = 'Variant Grams';
            //包含您的库存跟踪这个变体或产品
            $head[] = 'Variant Inventory Tracker';
            //您拥有该产品或变体的库存数量。
            $head[] = 'Variant Inventory Qty';
            //当此产品或变体的库存水平达到零时，如何处理订单。
            $head[] = 'Variant Inventory Policy';
            //使用的产品或变体履行服务。
            $head[] = 'Variant Fulfillment Service';
            //产品或变体的价格。不要在那里放置任何货币符号。
            $head[] = 'Variant Price';
            //产品或变体的“比较价格”。不要在那里放置任何货币符号
            $head[] = 'Variant Compare At Price';
            //要求运送的选项。有效值TRUE，FALSE或空白。
            $head[] = 'Variant Requires Shipping';
            //对这个变体申请税。有效值TRUE，FALSE或空白。
            $head[] = 'Variant Taxable';
            //产品的条形码，ISBN或UPC。
            $head[] = 'Variant Barcode';
            //输入产品图片的网址。
            $head[] = 'Image Src';
            //输入代表您希望图像显示在产品页面上的顺序的数字。
            $head[] = 'Image Position';
            //描述图片的文字。如果无法显示图像或屏幕阅读器越过图像，该文本将替换此元素，这很有用。
            $head[] = 'Image Alt Text';
            //说明产品是否为礼品卡。有效值是TRUE或FALSE。
            $head[] = 'Gift Card';
            $head[] = 'SEO Title';
            $head[] = 'SEO Description';
            $head[] = 'Google Shopping / Google Product Category';
            $head[] = 'Google Shopping / Gender';
            $head[] = 'Google Shopping / Age Group';
            $head[] = 'Google Shopping / MPN';
            $head[] = 'Google Shopping / AdWords Grouping';
            $head[] = 'Google Shopping / AdWords Labels';
            $head[] = 'Google Shopping / Condition';
            $head[] = 'Google Shopping / Custom Product';
            $head[] = 'Google Shopping / Custom Label 0';
            $head[] = 'Google Shopping / Custom Label 1';
            $head[] = 'Google Shopping / Custom Label 2';
            $head[] = 'Google Shopping / Custom Label 3';
            $head[] = 'Google Shopping / Custom Label 4';
            //变体图片的网址。
            $head[] = 'Variant Image';
            //有效值是`lb`，`kg`和`oz`。
            $head[] = 'Variant Weight Unit';
            //将Avalara代码应用于此产品的税收。
            $head[] = 'Variant Tax Code';

            //将头部导入数据中
            $data[] = $head;

            //获取头部数组总个数
            $h = count($head);

            //获取产品数据准备创建数据
            $res = $this->db1->get_where('db_magento_productlist',"`webname`='{$webname}' ")->result_array();
            foreach ($res as $row) {
                //创建一行数据
                $line = $this->addarray($h);
                $pname = $row['name'];//产品名称 
                $size = array();
                //把相应的数据填入数据库中
                //判断数据分组 和 tags
                   if( strpos(strtolower($pname), $search_costume) === false ){
                        if(strpos(strtolower($pname), $search_shoe) === false){
                                    $sizetype=0;
                                    $Tags = 'accessories';
                                }else{
                                  $sizetype=4;
                                  $size=$chart[4];
                                  $Tags = $shoetage;
                                }
                       }else{
                        $sizetype=1;
                        $size=$chart[1];
                        $Tags = $costumetage;
                       }

                //产品状态
                $Published = 'True';
                
                $Grams = $row['weight'] * 1000;
                //句柄
                $urlpos = strrpos($row['product_url'],'/');
                $handn = substr($row['product_url'], $urlpos+1,-5); //使用url
                $line = $this->addnewdate($head,$line,'Handle',$handn);
                $line = $this->addnewdate($head,$line,'Title',$pname);
                $key3 = array_search('Body (HTML)', $head);
                $line[$key3] = $row['description'];
                $line = $this->addnewdate($head,$line,'Body (HTML)',$row['description']);
                $line = $this->addnewdate($head,$line,'Vendor',$webname);//品牌
                $line = $this->addnewdate($head,$line,'Tags',$Tags);//标签
                $line = $this->addnewdate($head,$line,'Published',$Published);//表示产品是否在前台显示
                $sku = $row['sku'];//sku
                if($sku==null || $sku == '') continue;
                if ($sizetype != 0) {
                    if($sizetype == 1) $sku = $sku.'-'.$size[0];

                    if($sizetype == 1){
                        $line = $this->addnewdate($head,$line,'Option1 Name',$gdn);
                        $line = $this->addnewdate($head,$line,'Option1 Value',$gender[0]);
                        $line = $this->addnewdate($head,$line,'Option2 Name',$szn);
                        $line = $this->addnewdate($head,$line,'Option2 Value',$size[0]);
                    }else{
                        $line = $this->addnewdate($head,$line,'Option1 Name',$szn);
                        $line = $this->addnewdate($head,$line,'Option1 Value',$size[0]);
                    }
                }

                //价格
                if($row['special_price'] == '' || $row['special_price'] == null){
                    $Price = $row['price'];
                    $sprice = $row['special_price'];
                }else{
                    $Price = $row['special_price'];
                    $sprice = $row['price'];
                }

                //默认价格在原来的基础上增加10 货币单位
                $Price += 10;
                $sprice += 10;

                $line = $this->addnewdate($head,$line,'Variant SKU',$sku);
                $line = $this->addnewdate($head,$line,'Variant Grams',$Grams);//产品重量
                $line = $this->addnewdate($head,$line,'SEO Description',$row['description']);
                $line = $this->addnewdate($head,$line,'Variant Inventory Tracker','shopify');
                $line = $this->addnewdate($head,$line,'Variant Inventory Qty','1000');
                $line = $this->addnewdate($head,$line,'Variant Inventory Policy','deny');
                $line = $this->addnewdate($head,$line,'Variant Fulfillment Service','manual');
                $line = $this->addnewdate($head,$line,'Variant Price',$Price);
                $line = $this->addnewdate($head,$line,'Variant Compare At Price',$sprice);
                $line = $this->addnewdate($head,$line,'Variant Requires Shipping','true');
                $line = $this->addnewdate($head,$line,'Variant Taxable','false');

                //判断图片是否为空
                if($row['thumbnail_image'] != '' || $row['thumbnail_image'] != null){
                    $imgsrc = $row['thumbnail_image'];
                    $line = $this->addnewdate($head,$line,'Image Src',$imgsrc);
                    $line = $this->addnewdate($head,$line,'Image Position','1');
                }
                $line = $this->addnewdate($head,$line,'Gift Card','false');
                $line = $this->addnewdate($head,$line,'Variant Weight Unit','kg');

                //行数据加入到总数据中
                $data[] = $line;
                //判断是否需要变体
                //循环图片板块
                $imagarr =explode('|', $row['images']);
                $i=0;
                foreach ($imagarr as $value) {
                    $i++;
                    unset($linex);
                    $linex = $this->addarray($h);
                    $linex = $this->addnewdate($head,$linex,'Handle',$handn);
                    $linex = $this->addnewdate($head,$linex,'Image Src',$value);
                    $linex = $this->addnewdate($head,$linex,'Image Position',$i);
                    $data[] = $linex;
                }

                //增加尺码选项
                $sizen = count($size);
                for ($i=0; $i < $sizen ; $i++) { 
                    //创建新的一行
                    $liney = $this->addarray($h);
                    //把需要的数据放入其中
                    $liney = $this->addnewdate($head,$liney,'Handle',$handn);

                    $skuy=$row['sku'].'-'.$size[$i];
                    if($sizetype == '1'){
                        $liney = $this->addnewdate($head,$line,'Option1 Name',$gdn);
                        $liney = $this->addnewdate($head,$line,'Option1 Value',$gender[0]);
                        $liney = $this->addnewdate($head,$line,'Option2 Name',$szn);
                        $liney = $this->addnewdate($head,$line,'Option2 Value',$size[$i]); 
                    }else{
                        $liney = $this->addnewdate($head,$line,'Option1 Name',$szn);
                        $liney = $this->addnewdate($head,$line,'Option1 Value',$size[$i]);
                    }

                    $liney = $this->addnewdate($head,$liney,'Variant SKU',$skuy);
                    $liney = $this->addnewdate($head,$liney,'Variant Grams',$Grams);
                    $liney = $this->addnewdate($head,$liney,'Variant Inventory Tracker','shopify');
                    $liney = $this->addnewdate($head,$liney,'Variant Inventory Qty','1000');
                    $liney = $this->addnewdate($head,$liney,'Variant Inventory Policy','deny');
                    $liney = $this->addnewdate($head,$liney,'Variant Fulfillment Service','manual');
                    $liney = $this->addnewdate($head,$liney,'Variant Price',$Price);
                    $liney = $this->addnewdate($head,$line,'Variant Compare At Price',$sprice);
                    $liney = $this->addnewdate($head,$liney,'Variant Requires Shipping','true');
                    $liney = $this->addnewdate($head,$liney,'Variant Taxable','false');
                    $liney = $this->addnewdate($head,$liney,'Variant Weight Unit','kg');
                    $data[] = $liney;
                }

                //如果是衣服的话需要创建两次选项 性别，男女各一次
                if($sizetype == 1){
                    for ($i=0; $i < $sizen; $i++) { 
                        //创建新的一行
                        $linez = $this->addarray($h);
                        //把需要的数据放入其中
                        $linez = $this->addnewdate($head,$linez,'Handle',$handn);
                        $skuy = $row['sku'].'-'.$size[$i];
                        $linez = $this->addnewdate($head,$line,'Option1 Name',$gdn);
                        $linez = $this->addnewdate($head,$line,'Option1 Value',$gender[1]);
                        $linez = $this->addnewdate($head,$line,'Option2 Name',$szn);
                        $linez = $this->addnewdate($head,$line,'Option2 Value',$size[$i]);
                        $linez = $this->addnewdate($head,$linez,'Variant SKU',$skuy);
                        $linez = $this->addnewdate($head,$linez,'Variant Grams',$Grams);
                        $linez = $this->addnewdate($head,$linez,'Variant Inventory Tracker','shopify');
                        $linez = $this->addnewdate($head,$linez,'Variant Inventory Qty','1000');
                        $linez = $this->addnewdate($head,$linez,'Variant Inventory Policy','deny');
                        $linez = $this->addnewdate($head,$linez,'Variant Fulfillment Service','manual');
                        $linez = $this->addnewdate($head,$linez,'Variant Price',$Price);
                        $linez = $this->addnewdate($head,$line,'Variant Compare At Price',$sprice);
                        $linez = $this->addnewdate($head,$linez,'Variant Requires Shipping','true');
                        $linez = $this->addnewdate($head,$linez,'Variant Taxable','false');
                        $linez = $this->addnewdate($head,$linez,'Variant Weight Unit','kg');
                        $data[] = $linez;
                    }
                }

            //foreach 循环结束
            }
            //var_dump($data);
            //这一步可以准备写成csv文件
            $csvurl = '../'.$this->savecsv($data);
            //echo $csvurl;
            header("Location:$csvurl");
        //函数结束
        }

    //填充数组函数
     protected function addarray($i){
             $line=array();
             //根据已知标题数把，所有位置站位；
              for ($j=0; $j <=$i ; $j++) { 
              $line[$j]='';
               }
               return $line;
        }

    //添加数据到数组
     protected function addnewdate($arr,$newarr,$val,$newval){
         $key=array_search($val, $arr);
         $newarr[$key]=$newval;
         return $newarr;
        }
     protected   function savecsv($data){
          if(!is_dir('uploads/magento_shopfiy')){
            //如果不存在文件夹，则创建文件夹
            mkdir('uploads/magento_shopfiy');
            }
            $csvname=date('Y-m-d-H-i-s');
            // $csvname= 'Customers_Export1';
          $filename="uploads/magento_shopfiy/$csvname.csv";
          $fh = fopen($filename, 'w') or die("can't open $filename");
          foreach ($data as $sale_line) {
            if(fputcsv($fh, $sale_line)=== false){
              die("can't write csv line");

            }
          }
          fclose($fh) or die("can't close $filename");
          return $filename;
        }

}
?>

